<template>
  <div class="page-container">
    <div class="page-header">
      <h2 class="page-title">学生测试结果</h2>
      <el-tag v-if="adminInfo.level" type="info">{{ adminInfo.label }}</el-tag>
    </div>

    <el-card>

      <!-- 统计图表 -->
      <div class="statistics-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <div id="pieChart" class="chart"></div>
          </el-col>
          <el-col :span="12">
            <div id="barChart" class="chart"></div>
          </el-col>
        </el-row>
      </div>

      <!-- 测试记录表格 -->
      <el-table :data="testRecords" border style="width: 100%" v-loading="loading">
        <el-table-column prop="usercode" label="学号" />
        <el-table-column prop="userFullName" label="姓名" />
        <el-table-column prop="className" label="班级" />
        <el-table-column prop="majorName" label="专业" />
        <el-table-column prop="departmentName" label="学院" />
        <el-table-column prop="personalityType" label="MBTI类型" width="100">
          <template #default="{ row }">
            <el-tooltip :content="getPersonalityTypeDesc(row.personalityType)" placement="top">
              <el-tag>{{ row.personalityType }}</el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="得分详情" width="280">
          <template #default="{ row }">
            <div class="dimension-scores">
              <div class="score-row">
                <span>E-I: <b>{{ row.eScore || 0 }}</b>-<b>{{ row.iScore || 0 }}</b></span>
                <el-progress
                  :percentage="calculatePercentage(row.eScore, row.iScore)"
                  :format="() => ''"
                  :stroke-width="6"
                  :color="row.personalityType?.includes('E') ? '#409EFF' : '#CFE3FC'"
                />
              </div>
              <div class="score-row">
                <span>S-N: <b>{{ row.sScore || 0 }}</b>-<b>{{ row.nScore || 0 }}</b></span>
                <el-progress
                  :percentage="calculatePercentage(row.sScore, row.nScore)"
                  :format="() => ''"
                  :stroke-width="6"
                  :color="row.personalityType?.includes('S') ? '#409EFF' : '#CFE3FC'"
                />
              </div>
              <div class="score-row">
                <span>T-F: <b>{{ row.tScore || 0 }}</b>-<b>{{ row.fScore || 0 }}</b></span>
                <el-progress
                  :percentage="calculatePercentage(row.tScore, row.fScore)"
                  :format="() => ''"
                  :stroke-width="6"
                  :color="row.personalityType?.includes('T') ? '#409EFF' : '#CFE3FC'"
                />
              </div>
              <div class="score-row">
                <span>J-P: <b>{{ row.jScore || 0 }}</b>-<b>{{ row.pScore || 0 }}</b></span>
                <el-progress
                  :percentage="calculatePercentage(row.jScore, row.pScore)"
                  :format="() => ''"
                  :stroke-width="6"
                  :color="row.personalityType?.includes('J') ? '#409EFF' : '#CFE3FC'"
                />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="testDate" label="测试时间" width="170">
          <template #default="{ row }">
            {{ formatDate(row.testDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="primary" link @click="viewDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="pagination"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="handlePageChange"
      />
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="测试结果详情"
      width="800px"
    >
      <div v-if="selectedRecord">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学号">{{ selectedRecord.usercode }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ selectedRecord.userFullName }}</el-descriptions-item>
          <el-descriptions-item label="班级">{{ selectedRecord.className || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="专业">{{ selectedRecord.majorName || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="学院">{{ selectedRecord.departmentName || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="测试时间">{{ formatDate(selectedRecord.testDate) }}</el-descriptions-item>
          <el-descriptions-item label="MBTI类型">
            <el-tag>{{ selectedRecord.personalityType }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <div class="dimension-scores">
          <h3>维度得分</h3>
          <div class="dimension-score-row">
            <div class="dimension-score-item">
              <div class="dimension-score-label">外向(E) / 内向(I)</div>
              <el-progress
                :percentage="calculatePercentage(selectedRecord.eScore, selectedRecord.iScore)"
                :format="() => `E: ${selectedRecord.eScore || 0}`"
                :color="selectedRecord.personalityType?.includes('E') ? '#409EFF' : '#CFE3FC'"
              ></el-progress>
              <el-progress
                :percentage="calculatePercentage(selectedRecord.iScore, selectedRecord.eScore)"
                :format="() => `I: ${selectedRecord.iScore || 0}`"
                :color="selectedRecord.personalityType?.includes('I') ? '#67C23A' : '#E1F3D8'"
              ></el-progress>
            </div>
          </div>

          <div class="dimension-score-row">
            <div class="dimension-score-item">
              <div class="dimension-score-label">感觉(S) / 直觉(N)</div>
              <el-progress
                :percentage="calculatePercentage(selectedRecord.sScore, selectedRecord.nScore)"
                :format="() => `S: ${selectedRecord.sScore || 0}`"
                :color="selectedRecord.personalityType?.includes('S') ? '#409EFF' : '#CFE3FC'"
              ></el-progress>
              <el-progress
                :percentage="calculatePercentage(selectedRecord.nScore, selectedRecord.sScore)"
                :format="() => `N: ${selectedRecord.nScore || 0}`"
                :color="selectedRecord.personalityType?.includes('N') ? '#67C23A' : '#E1F3D8'"
              ></el-progress>
            </div>
          </div>

          <div class="dimension-score-row">
            <div class="dimension-score-item">
              <div class="dimension-score-label">思考(T) / 情感(F)</div>
              <el-progress
                :percentage="calculatePercentage(selectedRecord.tScore, selectedRecord.fScore)"
                :format="() => `T: ${selectedRecord.tScore || 0}`"
                :color="selectedRecord.personalityType?.includes('T') ? '#409EFF' : '#CFE3FC'"
              ></el-progress>
              <el-progress
                :percentage="calculatePercentage(selectedRecord.fScore, selectedRecord.tScore)"
                :format="() => `F: ${selectedRecord.fScore || 0}`"
                :color="selectedRecord.personalityType?.includes('F') ? '#67C23A' : '#E1F3D8'"
              ></el-progress>
            </div>
          </div>

          <div class="dimension-score-row">
            <div class="dimension-score-item">
              <div class="dimension-score-label">判断(J) / 知觉(P)</div>
              <el-progress
                :percentage="calculatePercentage(selectedRecord.jScore, selectedRecord.pScore)"
                :format="() => `J: ${selectedRecord.jScore || 0}`"
                :color="selectedRecord.personalityType?.includes('J') ? '#409EFF' : '#CFE3FC'"
              ></el-progress>
              <el-progress
                :percentage="calculatePercentage(selectedRecord.pScore, selectedRecord.jScore)"
                :format="() => `P: ${selectedRecord.pScore || 0}`"
                :color="selectedRecord.personalityType?.includes('P') ? '#67C23A' : '#E1F3D8'"
              ></el-progress>
            </div>
          </div>
        </div>

        <div class="personality-type-info" v-if="selectedTypeInfo">
          <h3>{{ selectedTypeInfo.code }} - {{ selectedTypeInfo.name }}</h3>
          <el-tabs>
            <el-tab-pane label="性格特点">
              <div v-html="selectedTypeInfo.description"></div>
            </el-tab-pane>
            <el-tab-pane label="职业建议">
              <div v-html="selectedTypeInfo.careerAdvice"></div>
            </el-tab-pane>
            <el-tab-pane label="学习风格">
              <div v-html="selectedTypeInfo.learningStyle"></div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useUserStore } from '../../stores/user'
import request from '../../utils/request'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

const userStore = useUserStore()

// 管理员信息
const adminInfo = computed(() => {
  let level = '';
  let label = '普通教师';
  let orgId = null;
  
  if (userStore.userInfo?.userType?.toLowerCase() === 'super_admin') {
    level = 'SUPER_ADMIN';
    label = '超级管理员';
    return { level, label, orgId };
  }
  
  if (!userStore.userInfo?.extraInfo) {
    return { level, label, orgId };
  }
  
  try {
    const extraInfo = JSON.parse(userStore.userInfo.extraInfo);
    level = extraInfo.admin_role || '';
    orgId = userStore.userInfo.orgId;
    
    switch (level) {
      case 'SCHOOL_ADMIN':
        label = '校级管理员';
        break;
      case 'DEPARTMENT_ADMIN':
        label = '院级管理员';
        break;
      case 'MAJOR_ADMIN':
        label = '系级管理员';
        break;
      case 'CLASS_ADMIN':
        label = '班级管理员';
        break;
    }
  } catch (e) {
    console.error('解析管理员角色失败:', e);
  }
  
  return { level, label, orgId };
});

// 数据
const testRecords = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const personalityTypes = ref([]);
const loading = ref(false);
const detailDialogVisible = ref(false);
const selectedRecord = ref(null);
const selectedTypeInfo = ref(null);

let pieChart = null;
let barChart = null;

// 方法


const loadPersonalityTypes = async () => {
  try {
    // 使用根路径而不是/list
    const response = await request.get('/personality-types');
    personalityTypes.value = response.data;
  } catch (error) {
    console.error('获取MBTI类型列表失败:', error);
    ElMessage.error('获取MBTI类型列表失败');
  }
};

const loadTestRecords = async () => {
  loading.value = true;
  try {
    let params = {
      page: currentPage.value,
      size: pageSize.value
    };
    
    // 根据管理员级别设置组织ID
    if (adminInfo.value.level === 'CLASS_ADMIN') {
      params.orgId = adminInfo.value.orgId;
      params.orgType = 'CLASS';
    } else if (adminInfo.value.level === 'MAJOR_ADMIN') {
      params.orgId = adminInfo.value.orgId;
      params.orgType = 'MAJOR';
    } else if (adminInfo.value.level === 'DEPARTMENT_ADMIN') {
      params.orgId = adminInfo.value.orgId;
      params.orgType = 'DEPARTMENT';
    }
    
    const response = await request.get('/test-records/statistics', { params });
    const data = response.data;
    
    // 处理数据，确保所有分数字段都存在
    if (data.detailedData) {
      data.detailedData = data.detailedData.map(record => {
        return {
          ...record,
          eScore: Number(record.eScore || 0),
          iScore: Number(record.iScore || 0),
          sScore: Number(record.sScore || 0),
          nScore: Number(record.nScore || 0),
          tScore: Number(record.tScore || 0),
          fScore: Number(record.fScore || 0),
          jScore: Number(record.jScore || 0),
          pScore: Number(record.pScore || 0)
        };
      });
    }
    
    testRecords.value = data.detailedData || [];
    total.value = data.total || 0;
    updateCharts(data);
  } catch (error) {
    console.error('获取测试记录失败:', error);
    ElMessage.error('获取测试记录失败');
  } finally {
    loading.value = false;
  }
};



const handlePageChange = (page) => {
  currentPage.value = page;
  loadTestRecords();
};

const formatDate = (date) => {
  if (!date) return '';
  return new Date(date).toLocaleString();
};

const calculatePercentage = (score1, score2) => {
  // 确保参数是数字
  const s1 = Number(score1 || 0);
  const s2 = Number(score2 || 0);
  
  // 防止除以零错误
  if (s1 === 0 && s2 === 0) return 50; // 如果两个分数都是0，显示中间位置
  
  // 计算百分比：score1 / (score1 + score2) * 100
  const total = s1 + s2;
  return Math.round((s1 / total) * 100);
};

const getPersonalityTypeDesc = (typeCode) => {
  const type = personalityTypes.value.find(t => t.code === typeCode);
  return type ? `${type.code} - ${type.name}` : typeCode;
};

const viewDetail = (record) => {
  // 确保分数字段都存在
  selectedRecord.value = {
    ...record,
    eScore: Number(record.eScore || 0),
    iScore: Number(record.iScore || 0),
    sScore: Number(record.sScore || 0),
    nScore: Number(record.nScore || 0),
    tScore: Number(record.tScore || 0),
    fScore: Number(record.fScore || 0),
    jScore: Number(record.jScore || 0),
    pScore: Number(record.pScore || 0)
  };
  selectedTypeInfo.value = personalityTypes.value.find(t => t.code === record.personalityType);
  detailDialogVisible.value = true;
};

// 图表相关
const initCharts = () => {
  pieChart = echarts.init(document.getElementById('pieChart'));
  barChart = echarts.init(document.getElementById('barChart'));
  
  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', () => {
    pieChart?.resize();
    barChart?.resize();
  });
};

const updateCharts = (data) => {
  if (!pieChart || !barChart) {
    setTimeout(() => initCharts(), 100);
    return;
  }
  
  const typeCounts = data.typeCounts || {};
  
  // 饼图配置
  const pieOption = {
    title: {
      text: 'MBTI类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 20,
      bottom: 20,
    },
    series: [
      {
        type: 'pie',
        radius: '55%',
        center: ['40%', '50%'],
        data: Object.entries(typeCounts).map(([type, count]) => ({
          name: type,
          value: count
        })).sort((a, b) => a.name.localeCompare(b.name)),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };

  // 柱状图配置
  const barOption = {
    title: {
      text: 'MBTI类型数量统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: Object.keys(typeCounts).sort(),
      axisLabel: {
        interval: 0,
        rotate: 45
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        type: 'bar',
        data: Object.keys(typeCounts).sort().map(key => typeCounts[key]),
        itemStyle: {
          color: function(params) {
            const colorList = [
              '#5470c6', '#91cc75', '#fac858', '#ee6666',
              '#73c0de', '#3ba272', '#fc8452', '#9a60b4',
              '#ea7ccc', '#6e7074', '#61a0a8', '#efa18d',
              '#a1a1a1', '#d16b16', '#8d7b6c', '#548292'
            ];
            return colorList[params.dataIndex % colorList.length];
          }
        }
      }
    ]
  };

  pieChart.setOption(pieOption);
  barChart.setOption(barOption);
};

// 生命周期
onMounted(() => {
  loadPersonalityTypes();
  setTimeout(() => {
    initCharts();
    loadTestRecords();
  }, 100);
});
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin-right: 10px;
  margin-bottom: 0;
}

.admin-tag {
  margin-left: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.statistics-section {
  margin-bottom: 20px;
}

.chart {
  width: 100%;
  height: 400px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 得分详情样式 */
.dimension-scores {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.score-row {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.score-row span {
  margin-bottom: 3px;
  font-size: 13px;
  display: flex;
  justify-content: space-between;
}

/* 详情对话框样式 */
.dimension-score-row {
  margin-bottom: 20px;
}

.dimension-score-item {
  width: 100%;
}

.dimension-score-label {
  font-weight: bold;
  margin-bottom: 8px;
}

.personality-type-info {
  margin-top: 30px;
}

/* 定制进度条样式 */
:deep(.el-progress-bar) {
  margin-right: 0;
}

:deep(.el-progress-bar__outer) {
  background-color: #f0f0f0;
  border-radius: 4px;
}

:deep(.el-progress-bar__inner) {
  border-radius: 4px;
  transition: width 0.6s ease;
}

:deep(.el-progress) {
  margin-bottom: 8px;
}

:deep(.el-progress-bar__innerText) {
  color: #333;
  font-size: 13px;
}
</style> 